package com.abby.regex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {
    private static final String ADDRESS = "中华人民共和国北京市朝阳区望京科技园创业园F座502室";
    public static void main(String[] args) {
        List<String> result = resolveAddress(ADDRESS);
        for (String info:result){
            System.out.println(info);
        }
    }

    /**
     * resolve the address,extracting the country info,province info and so on
     * 解析地址，提取地址中的国家，省份等信息
     * @param address the address to be resolved,待解析的地址
     * @return list of the address information,包含地址信息的List
     */
    private static List<String> resolveAddress(String address){
        List<String> matchedStrList = new ArrayList<>();

        //check if the value is illegal
        //检查地址的合法性
        if (address==null || address.isEmpty()){
           return matchedStrList;
        }
        address = address.trim();

        //pattern string of the regular expression
        //正则表达式的匹配字符串
        String patternExpression =  ".+?(国|省|自治区|自治州|市|县|镇|街道|街|(!小)区)";
        Pattern pattern = Pattern.compile(patternExpression);
        Matcher matcher = pattern.matcher(address);
        while(matcher.find()){
            matchedStrList.add(matcher.group());
        }

        //as the feature string of the last address info is not fixed,we should extract it separately
        //最后一个地址信息的字符串特征不固定，应该单独处理
        String lastMatched = matchedStrList.get(matchedStrList.size()-1);
        String lastInfo = null;
        int index = address.indexOf(lastMatched);
        if(index+lastMatched.length()<address.length()){
            lastInfo = address.substring(index+lastMatched.length());
        }

        if (lastInfo!=null){
            matchedStrList.add(lastInfo);
        }
        return matchedStrList;
    }
}
